<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    .content-box {
      width: 100%;
      height: 500px;
      border: 1px solid red;
      box-sizing: border-box;
    }
    .content-box > div> span:first-child{
      font-size: 18px;
      color: red;
      font-weight: 800;
    }
    .content-box > div> span:last-child{
      font-size: 18px;
      color: rgb(6, 64, 141);
      font-weight: 500;
    }
    .welcome-msg{
      color: pink;
      font-size: 20px;
      font-style: italic;
    }
  </style>
</head>

<body>
  <h1>国大聊天室</h1>
  <div class="content-box">
      <div>
        <span>甲：</span> <span>今天天气真好，中午我们去喝点什么。。。</span>
      </div>
      <div>
        <span>老A：</span> <span>可以啊，？？？</span>
      </div>
  </div>
  <div>
    <input type="text" id="inputContent" />
    <button type="button" id="sendBtn">发送</button>
  </div>
  <script>
    let ws = null;
    window.onload = function () {
      // 1. 创建一个websocket链接：
      ws = new WebSocket("ws://192.168.1.161:3333");
      // 2.当连接成功时,触发open事件:
      ws.onopen = function () {
        console.log("成功连接上服务器");
      };
      // 3.当收到服务器推送的信息时
      ws.onmessage = function (event) {
        // console.log(event); // 事件对象
        // console.log("收到服务器推送的消息：如下")
        // console.log(event.data);  //推送的内容
        let contentBox = document.getElementsByClassName('content-box')[0];
        contentBox.innerHTML += event.data;
      };
      // 4. 关闭事件
      ws.onclose = function () {
        console.log("客户端关闭了通信链接");
      };
      // 5. 错误事件
      ws.onerror = function (err) {
        console.log("客户端发生错误事件", err);

      }
    }
    window.onunload=function(){
      // 关闭链接
      ws.close();
    }

    // 点击发送时，发送聊天信息到服务器，服务器推送信息到客户端。再进行页面的数据渲染
    let sendBtn = document.getElementById('sendBtn');
    sendBtn.onclick = function(){
      let value = document.getElementById('inputContent').value;
      ws.send(` <div>
        <span>野狼：</span> <span>${value}</span>
      </div>`)
    }
  </script>
</body>

</html>